package com.book.controller;

import com.book.entity.Book;
import com.book.entity.Role;
import com.book.entity.User;
import com.book.request.getHotBookReq;
import com.book.service.BookService;
import com.book.service.CategoryService;
import com.book.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import utils.SecurityUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/")
public class HomeController extends BaseController {
    @Resource
    private UserService userService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private BookService bookService;

    @RequestMapping("/")
    public ModelAndView getIndex(HttpServletRequest request){
        ModelAndView mav=new ModelAndView();
//        User user=SecurityUtil.getCurrentUser();
        User user=(User) request.getSession().getAttribute("currentUser");
        if (user.getUserType().equals("admin")){
            mav.setViewName("admin/index");
        }else
            mav.setViewName("redirect/index");
        return mav;
    }

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request){
        ModelAndView mav=new ModelAndView();
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        return mav;
    }

    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request){
        ModelAndView mav=new ModelAndView();
        User currentUser=(User)request.getSession().getAttribute("currentUser");
        getHotBookReq req=new getHotBookReq();
        req.setCurrent(getPageNum(request));
        req.setSize(getPageSize(request));
        List<Book> hotBooks=bookService.getHotBooks(req);
        mav.addObject("currentUser",currentUser);
        mav.addObject("hotBooks",hotBooks);
        mav.addObject("recommendBooks",bookService.getRecommendBooks());
        mav.setViewName("index");
        return mav;
    }

    @RequestMapping(value="/logout")
    public String logout(HttpServletRequest request,ModelMap m){
        Subject subject= SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    @RequestMapping("/unauth")
    public String unauth(ModelMap m){
        if(!SecurityUtils.getSubject().isAuthenticated()){
            return "login";
        }
        return "login";
    }

}
